package com.lifeverse.service;

import com.lifeverse.entity.NetworkHealthMetrics;
import com.lifeverse.repository.NetworkHealthMetricsRepository;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 网络异常检测服务
 * 实现基础的异常检测算法
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NetworkAnomalyDetector {
    
    private final NetworkHealthMetricsRepository metricsRepository;
    
    /**
     * 异常类型枚举
     */
    public enum AnomalyType {
        PERFORMANCE_DEGRADATION("性能下降", "系统响应时间或吞吐量异常"),
        CONNECTIVITY_LOSS("连接丢失", "网络连通性显著下降"),
        STABILITY_ISSUE("稳定性问题", "网络稳定性出现问题"),
        ACTIVITY_ANOMALY("活跃度异常", "网络活跃度异常变化"),
        ERROR_SPIKE("错误激增", "错误率突然增加"),
        AVAILABILITY_DROP("可用性下降", "系统可用性显著下降"),
        LOAD_ANOMALY("负载异常", "系统负载异常"),
        TRUST_DECLINE("信任度下降", "网络信任度显著下降"),
        DIVERSITY_LOSS("多样性丢失", "网络多样性下降"),
        INNOVATION_STAGNATION("创新停滞", "创新能力显著下降");
        
        private final String displayName;
        private final String description;
        
        AnomalyType(String displayName, String description) {
            this.displayName = displayName;
            this.description = description;
        }
        
        public String getDisplayName() {
            return displayName;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 异常严重程度枚举
     */
    public enum AnomalySeverity {
        LOW("低", 1),
        MEDIUM("中", 2),
        HIGH("高", 3),
        CRITICAL("严重", 4);
        
        private final String displayName;
        private final int level;
        
        AnomalySeverity(String displayName, int level) {
            this.displayName = displayName;
            this.level = level;
        }
        
        public String getDisplayName() {
            return displayName;
        }
        
        public int getLevel() {
            return level;
        }
    }
    
    /**
     * 异常检测结果
     */
    public static class AnomalyDetectionResult {
        private boolean hasAnomalies;
        private List<DetectedAnomaly> anomalies;
        private BigDecimal overallAnomalyScore;
        private String summary;
        private List<String> recommendations;
        
        public AnomalyDetectionResult() {
            this.anomalies = new ArrayList<>();
            this.recommendations = new ArrayList<>();
        }
        
        // Getters and Setters
        public boolean isHasAnomalies() { return hasAnomalies; }
        public void setHasAnomalies(boolean hasAnomalies) { this.hasAnomalies = hasAnomalies; }
        
        public List<DetectedAnomaly> getAnomalies() { return anomalies; }
        public void setAnomalies(List<DetectedAnomaly> anomalies) { this.anomalies = anomalies; }
        
        public BigDecimal getOverallAnomalyScore() { return overallAnomalyScore; }
        public void setOverallAnomalyScore(BigDecimal overallAnomalyScore) { this.overallAnomalyScore = overallAnomalyScore; }
        
        public String getSummary() { return summary; }
        public void setSummary(String summary) { this.summary = summary; }
        
        public List<String> getRecommendations() { return recommendations; }
        public void setRecommendations(List<String> recommendations) { this.recommendations = recommendations; }
    }
    
    /**
     * 检测到的异常
     */
    public static class DetectedAnomaly {
        private AnomalyType type;
        private AnomalySeverity severity;
        private BigDecimal score;
        private String description;
        private BigDecimal currentValue;
        private BigDecimal expectedValue;
        private BigDecimal deviation;
        private LocalDateTime detectedAt;
        private Map<String, Object> details;
        
        public DetectedAnomaly() {
            this.details = new HashMap<>();
        }
        
        // Getters and Setters
        public AnomalyType getType() { return type; }
        public void setType(AnomalyType type) { this.type = type; }
        
        public AnomalySeverity getSeverity() { return severity; }
        public void setSeverity(AnomalySeverity severity) { this.severity = severity; }
        
        public BigDecimal getScore() { return score; }
        public void setScore(BigDecimal score) { this.score = score; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public BigDecimal getCurrentValue() { return currentValue; }
        public void setCurrentValue(BigDecimal currentValue) { this.currentValue = currentValue; }
        
        public BigDecimal getExpectedValue() { return expectedValue; }
        public void setExpectedValue(BigDecimal expectedValue) { this.expectedValue = expectedValue; }
        
        public BigDecimal getDeviation() { return deviation; }
        public void setDeviation(BigDecimal deviation) { this.deviation = deviation; }
        
        public LocalDateTime getDetectedAt() { return detectedAt; }
        public void setDetectedAt(LocalDateTime detectedAt) { this.detectedAt = detectedAt; }
        
        public Map<String, Object> getDetails() { return details; }
        public void setDetails(Map<String, Object> details) { this.details = details; }
    }
    
    /**
     * 检测网络异常
     */
    public AnomalyDetectionResult detectAnomalies(NetworkHealthMetrics currentMetrics) {
        log.debug("开始检测网络异常: {}", currentMetrics.getNetworkIdentifier());
        
        AnomalyDetectionResult result = new AnomalyDetectionResult();
        result.setHasAnomalies(false);
        
        // 获取历史数据用于基线比较
        List<NetworkHealthMetrics> historicalMetrics = getHistoricalMetrics(
                currentMetrics.getNetworkType(), 
                currentMetrics.getNetworkIdentifier(), 
                30 // 30天历史数据
        );
        
        if (historicalMetrics.isEmpty()) {
            log.debug("没有足够的历史数据进行异常检测");
            result.setOverallAnomalyScore(BigDecimal.valueOf(100)); // 无异常
            result.setSummary("没有足够的历史数据进行异常检测");
            return result;
        }
        
        // 执行各种异常检测
        detectPerformanceAnomalies(currentMetrics, historicalMetrics, result);
        detectConnectivityAnomalies(currentMetrics, historicalMetrics, result);
        detectStabilityAnomalies(currentMetrics, historicalMetrics, result);
        detectActivityAnomalies(currentMetrics, historicalMetrics, result);
        detectErrorAnomalies(currentMetrics, historicalMetrics, result);
        detectAvailabilityAnomalies(currentMetrics, historicalMetrics, result);
        detectTrustAnomalies(currentMetrics, historicalMetrics, result);
        detectDiversityAnomalies(currentMetrics, historicalMetrics, result);
        detectInnovationAnomalies(currentMetrics, historicalMetrics, result);
        
        // 计算总体异常评分
        calculateOverallAnomalyScore(result);
        
        // 生成摘要和建议
        generateSummaryAndRecommendations(result);
        
        result.setHasAnomalies(!result.getAnomalies().isEmpty());
        
        log.debug("异常检测完成: 发现 {} 个异常，总体异常评分: {}", 
                result.getAnomalies().size(), result.getOverallAnomalyScore());
        
        return result;
    }
    
    /**
     * 检测性能异常
     */
    private void detectPerformanceAnomalies(NetworkHealthMetrics current, 
                                          List<NetworkHealthMetrics> historical, 
                                          AnomalyDetectionResult result) {
        // 响应时间异常检测
        double avgResponseTime = historical.stream()
                .mapToLong(NetworkHealthMetrics::getResponseTimeMs)
                .average()
                .orElse(100.0);
        
        double responseTimeThreshold = avgResponseTime * 2.0; // 2倍阈值
        
        if (current.getResponseTimeMs() > responseTimeThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.PERFORMANCE_DEGRADATION);
            anomaly.setCurrentValue(BigDecimal.valueOf(current.getResponseTimeMs()));
            anomaly.setExpectedValue(BigDecimal.valueOf(avgResponseTime));
            anomaly.setDeviation(BigDecimal.valueOf(current.getResponseTimeMs() - avgResponseTime));
            anomaly.setDescription("响应时间异常增加");
            anomaly.setDetectedAt(LocalDateTime.now());
            
            // 计算严重程度
            double deviationRatio = current.getResponseTimeMs() / avgResponseTime;
            if (deviationRatio > 5) {
                anomaly.setSeverity(AnomalySeverity.CRITICAL);
                anomaly.setScore(BigDecimal.valueOf(90));
            } else if (deviationRatio > 3) {
                anomaly.setSeverity(AnomalySeverity.HIGH);
                anomaly.setScore(BigDecimal.valueOf(70));
            } else {
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(50));
            }
            
            result.getAnomalies().add(anomaly);
        }
        
        // 吞吐量异常检测
        double avgThroughput = historical.stream()
                .mapToDouble(m -> m.getThroughputPerSecond().doubleValue())
                .average()
                .orElse(500.0);
        
        double throughputThreshold = avgThroughput * 0.5; // 50%阈值
        
        if (current.getThroughputPerSecond().doubleValue() < throughputThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.PERFORMANCE_DEGRADATION);
            anomaly.setCurrentValue(current.getThroughputPerSecond());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgThroughput));
            anomaly.setDeviation(BigDecimal.valueOf(avgThroughput - current.getThroughputPerSecond().doubleValue()));
            anomaly.setDescription("吞吐量异常下降");
            anomaly.setDetectedAt(LocalDateTime.now());
            
            double deviationRatio = current.getThroughputPerSecond().doubleValue() / avgThroughput;
            if (deviationRatio < 0.2) {
                anomaly.setSeverity(AnomalySeverity.CRITICAL);
                anomaly.setScore(BigDecimal.valueOf(90));
            } else if (deviationRatio < 0.4) {
                anomaly.setSeverity(AnomalySeverity.HIGH);
                anomaly.setScore(BigDecimal.valueOf(70));
            } else {
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(50));
            }
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测连通性异常
     */
    private void detectConnectivityAnomalies(NetworkHealthMetrics current, 
                                           List<NetworkHealthMetrics> historical, 
                                           AnomalyDetectionResult result) {
        double avgConnectivity = historical.stream()
                .mapToDouble(m -> m.getConnectivityScore().doubleValue())
                .average()
                .orElse(70.0);
        
        double connectivityThreshold = avgConnectivity * 0.7; // 30%下降阈值
        
        if (current.getConnectivityScore().doubleValue() < connectivityThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.CONNECTIVITY_LOSS);
            anomaly.setCurrentValue(current.getConnectivityScore());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgConnectivity));
            anomaly.setDeviation(BigDecimal.valueOf(avgConnectivity - current.getConnectivityScore().doubleValue()));
            anomaly.setDescription("网络连通性显著下降");
            anomaly.setDetectedAt(LocalDateTime.now());
            
            double deviationRatio = current.getConnectivityScore().doubleValue() / avgConnectivity;
            if (deviationRatio < 0.5) {
                anomaly.setSeverity(AnomalySeverity.CRITICAL);
                anomaly.setScore(BigDecimal.valueOf(85));
            } else if (deviationRatio < 0.7) {
                anomaly.setSeverity(AnomalySeverity.HIGH);
                anomaly.setScore(BigDecimal.valueOf(65));
            } else {
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(45));
            }
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测稳定性异常
     */
    private void detectStabilityAnomalies(NetworkHealthMetrics current, 
                                        List<NetworkHealthMetrics> historical, 
                                        AnomalyDetectionResult result) {
        double avgStability = historical.stream()
                .mapToDouble(m -> m.getStabilityScore().doubleValue())
                .average()
                .orElse(70.0);
        
        double stabilityThreshold = avgStability * 0.8; // 20%下降阈值
        
        if (current.getStabilityScore().doubleValue() < stabilityThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.STABILITY_ISSUE);
            anomaly.setCurrentValue(current.getStabilityScore());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgStability));
            anomaly.setDeviation(BigDecimal.valueOf(avgStability - current.getStabilityScore().doubleValue()));
            anomaly.setDescription("网络稳定性出现问题");
            anomaly.setDetectedAt(LocalDateTime.now());
            
            double deviationRatio = current.getStabilityScore().doubleValue() / avgStability;
            if (deviationRatio < 0.6) {
                anomaly.setSeverity(AnomalySeverity.HIGH);
                anomaly.setScore(BigDecimal.valueOf(75));
            } else {
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(55));
            }
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测活跃度异常
     */
    private void detectActivityAnomalies(NetworkHealthMetrics current, 
                                       List<NetworkHealthMetrics> historical, 
                                       AnomalyDetectionResult result) {
        double avgActivity = historical.stream()
                .mapToDouble(m -> m.getActivityScore().doubleValue())
                .average()
                .orElse(60.0);
        
        double activityLowThreshold = avgActivity * 0.6; // 40%下降阈值
        double activityHighThreshold = avgActivity * 1.5; // 50%增长阈值
        
        if (current.getActivityScore().doubleValue() < activityLowThreshold || 
            current.getActivityScore().doubleValue() > activityHighThreshold) {
            
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.ACTIVITY_ANOMALY);
            anomaly.setCurrentValue(current.getActivityScore());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgActivity));
            anomaly.setDeviation(BigDecimal.valueOf(Math.abs(avgActivity - current.getActivityScore().doubleValue())));
            anomaly.setDetectedAt(LocalDateTime.now());
            
            if (current.getActivityScore().doubleValue() < activityLowThreshold) {
                anomaly.setDescription("网络活跃度异常下降");
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(60));
            } else {
                anomaly.setDescription("网络活跃度异常增加");
                anomaly.setSeverity(AnomalySeverity.LOW);
                anomaly.setScore(BigDecimal.valueOf(30));
            }
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测错误异常
     */
    private void detectErrorAnomalies(NetworkHealthMetrics current, 
                                    List<NetworkHealthMetrics> historical, 
                                    AnomalyDetectionResult result) {
        double avgErrorRate = historical.stream()
                .mapToDouble(m -> m.getErrorRate().doubleValue())
                .average()
                .orElse(2.0);
        
        double errorThreshold = Math.max(5.0, avgErrorRate * 2.0); // 2倍或5%阈值
        
        if (current.getErrorRate().doubleValue() > errorThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.ERROR_SPIKE);
            anomaly.setCurrentValue(current.getErrorRate());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgErrorRate));
            anomaly.setDeviation(BigDecimal.valueOf(current.getErrorRate().doubleValue() - avgErrorRate));
            anomaly.setDescription("错误率异常增加");
            anomaly.setDetectedAt(LocalDateTime.now());
            
            if (current.getErrorRate().doubleValue() > 15) {
                anomaly.setSeverity(AnomalySeverity.CRITICAL);
                anomaly.setScore(BigDecimal.valueOf(95));
            } else if (current.getErrorRate().doubleValue() > 10) {
                anomaly.setSeverity(AnomalySeverity.HIGH);
                anomaly.setScore(BigDecimal.valueOf(80));
            } else {
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(60));
            }
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测可用性异常
     */
    private void detectAvailabilityAnomalies(NetworkHealthMetrics current, 
                                           List<NetworkHealthMetrics> historical, 
                                           AnomalyDetectionResult result) {
        double avgAvailability = historical.stream()
                .mapToDouble(m -> m.getAvailability().doubleValue())
                .average()
                .orElse(98.0);
        
        double availabilityThreshold = Math.min(95.0, avgAvailability - 5.0); // 5%下降阈值
        
        if (current.getAvailability().doubleValue() < availabilityThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.AVAILABILITY_DROP);
            anomaly.setCurrentValue(current.getAvailability());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgAvailability));
            anomaly.setDeviation(BigDecimal.valueOf(avgAvailability - current.getAvailability().doubleValue()));
            anomaly.setDescription("系统可用性显著下降");
            anomaly.setDetectedAt(LocalDateTime.now());
            
            if (current.getAvailability().doubleValue() < 90) {
                anomaly.setSeverity(AnomalySeverity.CRITICAL);
                anomaly.setScore(BigDecimal.valueOf(90));
            } else if (current.getAvailability().doubleValue() < 95) {
                anomaly.setSeverity(AnomalySeverity.HIGH);
                anomaly.setScore(BigDecimal.valueOf(75));
            } else {
                anomaly.setSeverity(AnomalySeverity.MEDIUM);
                anomaly.setScore(BigDecimal.valueOf(55));
            }
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测信任度异常
     */
    private void detectTrustAnomalies(NetworkHealthMetrics current, 
                                    List<NetworkHealthMetrics> historical, 
                                    AnomalyDetectionResult result) {
        double avgTrust = historical.stream()
                .mapToDouble(m -> m.getTrustScore().doubleValue())
                .average()
                .orElse(70.0);
        
        double trustThreshold = avgTrust * 0.8; // 20%下降阈值
        
        if (current.getTrustScore().doubleValue() < trustThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.TRUST_DECLINE);
            anomaly.setCurrentValue(current.getTrustScore());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgTrust));
            anomaly.setDeviation(BigDecimal.valueOf(avgTrust - current.getTrustScore().doubleValue()));
            anomaly.setDescription("网络信任度显著下降");
            anomaly.setDetectedAt(LocalDateTime.now());
            anomaly.setSeverity(AnomalySeverity.MEDIUM);
            anomaly.setScore(BigDecimal.valueOf(50));
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测多样性异常
     */
    private void detectDiversityAnomalies(NetworkHealthMetrics current, 
                                        List<NetworkHealthMetrics> historical, 
                                        AnomalyDetectionResult result) {
        double avgDiversity = historical.stream()
                .mapToDouble(m -> m.getDiversityScore().doubleValue())
                .average()
                .orElse(60.0);
        
        double diversityThreshold = avgDiversity * 0.7; // 30%下降阈值
        
        if (current.getDiversityScore().doubleValue() < diversityThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.DIVERSITY_LOSS);
            anomaly.setCurrentValue(current.getDiversityScore());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgDiversity));
            anomaly.setDeviation(BigDecimal.valueOf(avgDiversity - current.getDiversityScore().doubleValue()));
            anomaly.setDescription("网络多样性下降");
            anomaly.setDetectedAt(LocalDateTime.now());
            anomaly.setSeverity(AnomalySeverity.LOW);
            anomaly.setScore(BigDecimal.valueOf(35));
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 检测创新异常
     */
    private void detectInnovationAnomalies(NetworkHealthMetrics current, 
                                         List<NetworkHealthMetrics> historical, 
                                         AnomalyDetectionResult result) {
        double avgInnovation = historical.stream()
                .mapToDouble(m -> m.getInnovationScore().doubleValue())
                .average()
                .orElse(60.0);
        
        double innovationThreshold = avgInnovation * 0.6; // 40%下降阈值
        
        if (current.getInnovationScore().doubleValue() < innovationThreshold) {
            DetectedAnomaly anomaly = new DetectedAnomaly();
            anomaly.setType(AnomalyType.INNOVATION_STAGNATION);
            anomaly.setCurrentValue(current.getInnovationScore());
            anomaly.setExpectedValue(BigDecimal.valueOf(avgInnovation));
            anomaly.setDeviation(BigDecimal.valueOf(avgInnovation - current.getInnovationScore().doubleValue()));
            anomaly.setDescription("创新能力显著下降");
            anomaly.setDetectedAt(LocalDateTime.now());
            anomaly.setSeverity(AnomalySeverity.LOW);
            anomaly.setScore(BigDecimal.valueOf(40));
            
            result.getAnomalies().add(anomaly);
        }
    }
    
    /**
     * 计算总体异常评分
     */
    private void calculateOverallAnomalyScore(AnomalyDetectionResult result) {
        if (result.getAnomalies().isEmpty()) {
            result.setOverallAnomalyScore(BigDecimal.valueOf(100)); // 无异常
            return;
        }
        
        // 计算加权异常评分
        double totalWeightedScore = 0;
        double totalWeight = 0;
        
        for (DetectedAnomaly anomaly : result.getAnomalies()) {
            double weight = anomaly.getSeverity().getLevel();
            totalWeightedScore += anomaly.getScore().doubleValue() * weight;
            totalWeight += weight;
        }
        
        double avgAnomalyScore = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;
        
        // 异常评分越高表示异常越严重，所以正常评分 = 100 - 异常评分
        BigDecimal overallScore = BigDecimal.valueOf(Math.max(0, 100 - avgAnomalyScore))
                .setScale(2, RoundingMode.HALF_UP);
        
        result.setOverallAnomalyScore(overallScore);
    }
    
    /**
     * 生成摘要和建议
     */
    private void generateSummaryAndRecommendations(AnomalyDetectionResult result) {
        if (result.getAnomalies().isEmpty()) {
            result.setSummary("网络运行正常，未检测到异常");
            result.getRecommendations().add("继续保持当前的网络运行状态");
            return;
        }
        
        // 生成摘要
        Map<AnomalySeverity, Long> severityCount = result.getAnomalies().stream()
                .collect(Collectors.groupingBy(DetectedAnomaly::getSeverity, Collectors.counting()));
        
        StringBuilder summary = new StringBuilder();
        summary.append("检测到 ").append(result.getAnomalies().size()).append(" 个异常：");
        
        for (Map.Entry<AnomalySeverity, Long> entry : severityCount.entrySet()) {
            summary.append(" ").append(entry.getKey().getDisplayName())
                   .append("级 ").append(entry.getValue()).append(" 个");
        }
        
        result.setSummary(summary.toString());
        
        // 生成建议
        Set<String> recommendations = new HashSet<>();
        
        for (DetectedAnomaly anomaly : result.getAnomalies()) {
            switch (anomaly.getType()) {
                case PERFORMANCE_DEGRADATION:
                    recommendations.add("优化系统性能，检查资源瓶颈");
                    recommendations.add("考虑扩容或负载均衡");
                    break;
                case CONNECTIVITY_LOSS:
                    recommendations.add("检查网络连接，修复断开的链路");
                    recommendations.add("增加冗余连接提高网络鲁棒性");
                    break;
                case STABILITY_ISSUE:
                    recommendations.add("加强关系维护，提高网络稳定性");
                    recommendations.add("识别并解决不稳定因素");
                    break;
                case ACTIVITY_ANOMALY:
                    recommendations.add("调整网络活跃度到正常水平");
                    recommendations.add("分析活跃度变化的根本原因");
                    break;
                case ERROR_SPIKE:
                    recommendations.add("立即调查错误原因并修复");
                    recommendations.add("加强错误监控和预防机制");
                    break;
                case AVAILABILITY_DROP:
                    recommendations.add("提高系统可用性，减少停机时间");
                    recommendations.add("实施高可用性架构");
                    break;
                case TRUST_DECLINE:
                    recommendations.add("重建网络信任，加强透明度");
                    recommendations.add("实施信任修复机制");
                    break;
                case DIVERSITY_LOSS:
                    recommendations.add("增加网络多样性，引入新的参与者");
                    break;
                case INNOVATION_STAGNATION:
                    recommendations.add("激励创新活动，提供创新支持");
                    break;
            }
        }
        
        result.setRecommendations(new ArrayList<>(recommendations));
    }
    
    /**
     * 获取历史指标数据
     */
    private List<NetworkHealthMetrics> getHistoricalMetrics(NetworkHealthMetrics.NetworkType networkType, 
                                                           String networkIdentifier, 
                                                           int days) {
        LocalDateTime since = LocalDateTime.now().minusDays(days);
        
        if (networkIdentifier != null) {
            return metricsRepository.findByNetworkTypeAndMeasurementTimeBetween(
                    networkType, since, LocalDateTime.now());
        } else {
            return metricsRepository.findByNetworkTypeAndMeasurementTimeBetween(
                    networkType, since, LocalDateTime.now());
        }
    }
    
    /**
     * 批量检测异常
     */
    public Map<String, AnomalyDetectionResult> batchDetectAnomalies() {
        Map<String, AnomalyDetectionResult> results = new HashMap<>();
        
        // 检测全局网络异常
        List<NetworkHealthMetrics> globalMetrics = metricsRepository
                .findLatestGlobalMetrics(org.springframework.data.domain.PageRequest.of(0, 1));
        
        if (!globalMetrics.isEmpty()) {
            AnomalyDetectionResult globalResult = detectAnomalies(globalMetrics.get(0));
            results.put("GLOBAL_NETWORK", globalResult);
        }
        
        // 检测各群体网络异常
        List<NetworkHealthMetrics> groupMetrics = metricsRepository
                .findByNetworkType(NetworkHealthMetrics.NetworkType.GROUP_BASED);
        
        for (NetworkHealthMetrics metrics : groupMetrics) {
            if (metrics.getNetworkIdentifier() != null) {
                AnomalyDetectionResult groupResult = detectAnomalies(metrics);
                results.put(metrics.getNetworkIdentifier(), groupResult);
            }
        }
        
        return results;
    }
}